package util;

import java.sql.*;
import java.util.List;

public class BaseUtil {
    //1.定义变量
    private Connection conn;
    private PreparedStatement pps;
    private ResultSet rst;
    private int count; //存储受影响的行数
    private static String driverClass = "com.mysql.cj.jdbc.Driver";
    private static String userName = "root";
    private static String passWord = "123456";
    private static String url = "jdbc:mysql://localhost:3306/xsglxt?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";

    //2.加载驱动
    static {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //3.获得链接
    protected Connection getConn() throws SQLException {
        conn = DriverManager.getConnection(url, userName, passWord);
        return conn;
    }
    //4.得到预状态通道
    protected PreparedStatement getPps(String sql) throws SQLException {
        pps = getConn().prepareStatement(sql);
        return pps;
    }
    //5.绑定参数 List保存占位符的值
    protected void param(List list) throws SQLException {
        if (list!=null&&list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                pps.setObject(i+1,list.get(i));
            }
        }
    }
    //6.执行操作（增删改）
    protected int stUpdate(String sql,List list) throws SQLException {
        getPps(sql);
        param(list);
        count = pps.executeUpdate();
        return count;
    }
    //7.执行操作（查询）
    protected ResultSet stSelect(String sql,List list) throws SQLException {
        getPps(sql);
        param(list);
        rst = pps.executeQuery();
        return rst;
    }
    protected ResultSet stSelect(String sql) throws SQLException {
        getPps(sql);
        rst = pps.executeQuery();
        return rst;
    }
    //8.关闭资源
    protected void closeAll() throws SQLException {
        if (rst != null) {
            rst.close();
        }
        if (pps != null) {
            pps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
